<template>
  <BasicModal :width="1500" v-bind="$attrs" :title="getTitle"
    :canFullscreen="false" :centered="true" :destroyOnClose="true" :showCancelBtn="false" :showOkBtn="false"
    :bodyStyle="{height:'calc(100vh - 150px)', overflow:'hidden'}"
    @register="registerModal"
  >
  <split splitHeight="calc(100vh-5px)" leftWidth="900" style="overflow: hidden">
    <template #paneL>
      <BasicTable @register="registerTable" 
        :onRowClick="handleClick" 
        :onRowDbClick="handleDblclick" 
        :rowClassName="rowClassName" 
        :loading="loading"
      >
        <template #diffFmt="{text, record}">
          <span v-if="record?.hasDiff === 0">
            <a-icon type="check-circle" style="color: red" />
          </span>
          <span v-if="record?.hasDiff === 1">
            <a-icon type="close-circle" style="color: green" />
          </span>
          <span v-if="record?.hasDiff === 2">
            <a-icon type="close-circle" style="color: blue" />
          </span>
        </template>
      </BasicTable>
    </template>
    <template #paneR>
      <div class="jeecg-basic-table jeecg-basic-table-form-container" style="margin-top: 12px; margin-right: 10px; border-bottom:1px #E5E7E8 solid; padding:0;">
      <table class="orderTable" id="buctable">
        <tbody>
        <tr class="listBg">
          <th width="40"></th>
          <th width="130" class="text-center font-bold font-size-4">系统收支流水</th>
          <th width="130" class="text-center font-bold">订单收支流水</th>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">编号</td>
          <td class="text-left" :class="bankRunning.idcolor">{{bankRunning.id}}</td>
          <td class="text-left" :class="bankRunning.idcolor">{{account.id}}</td>
        </tr>
        <tr>
          <td class="bg-green-50">部门</td>
          <td class="text-left">{{ renderDict(bankRunning.ddlx, 'ddlxType') }}</td>
          <td class="text-left">{{ renderDict(account.ddlx, 'ddlxType') }}</td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">订单</td>
          <td class="text-left">{{bankRunning.orderId}}</td>
          <td class="text-left">{{account.orderId}}</td>
        </tr>
        <tr>
          <td class="bg-green-50">收入</td>
          <td class="text-left text-green-500">{{renderMoney(bankRunning.srje)}}</td>
          <td class="text-left text-green-500">{{renderMoney(account.srje)}}</td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">支出</td>
          <td class="text-left text-purple-500">{{renderMoney(bankRunning.zcje)}}</td>
          <td class="text-left text-purple-500">{{renderMoney(account.zcje)}}</td>
        </tr>
        <tr>
          <td class="bg-green-50">对方</td>
          <td class="text-left">{{bankRunning.dfzh}}</td>
          <td class="text-left">{{account.dfzh}}</td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">状态</td>
          <td class="text-left" :class="bankRunning.shbj == 1 ? 'text-rose-600' : 'text-green-600'"> 
            {{ bankRunning.shbj == 1 ? '已审' : bankRunning.shbj == 0 ? '未审' : ''}} 
          </td>
          <td class="text-left" :class="renderStatus(account.shbj, 'color')">{{ renderStatus(account.shbj, 'text') }} </td>
        </tr>
        <tr>
          <td class="bg-green-50">方式</td>
          <td class="text-left"> {{ bankRunning.sffsZw }} </td>
          <td class="text-left">{{ account.sffsZw }}</td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">录入</td>
          <td class="text-left">{{bankRunning.lrsj}}</td>
          <td class="text-left">{{account.lrsj}}</td>
        </tr>
        <tr>
          <td class="bg-green-50">审核</td>
          <td class="text-left">{{bankRunning.gxsj}}</td>
          <td class="text-left">{{account.gxsj}}</td>
        </tr>
        <tr class="listBg">
          <td class="bg-green-50">备注</td>
          <td class="text-left">{{bankRunning.bz}}</td>
          <td class="text-left">{{account.bz}}</td>
        </tr>
        </tbody>
      </table> 
      </div>

      <!--订单收支 2025-08-25 qindl---->
      <div class="listtab1" id="con_menu_3" style="margin-top: 12px; margin-right: 10px; border-bottom:1px #E5E7E8 solid; padding:0;">
      <table class="orderTable" id="accounttable" v-if="accountList?.optionList">
        <thead><tr> <th colspan="12"> 收付项目 </th> </tr></thead>
        <tbody>
          <tr class="listBg">
            <th width="40"></th>
            <th width="260">收付名称</th>
            <th width="80">收入</th>
            <th width="80">支出</th>
            <th width="100">审核时间</th>
            <th width="100">审核人</th>
          </tr>
        </tbody>
        <tbody v-for="(list, index) in accountList.optionList" :key="index">
          <tr :class="index % 2 == 0 ? 'listBg' : 'cor'">
            <td>{{ index + 1 }}</td>
            <td class="text-left">{{ list.sflx == '1' ? list.customerPathName : list.cooperatorPathName }}</td>
            <td class="text-right text-red-500">{{ formatAmount(list.skje) }}</td>
            <td class="text-right text-green-500">{{ formatAmount(list.fkje) }}</td>
            <td>{{ list.shsj }}</td>
            <td>{{ list.shrName }}</td>
          </tr>
        </tbody>
        <tfoot>
          <tr>
            <td>&nbsp;</td>
            <td class="tips">小计</td>
            <td class="tips align--right fwb text-red-500">{{ formatAmount(accountList.sumskje) }}</td>
            <td class="tips align--right fwb text-green-500">{{ formatAmount(accountList.sumfkje) }}</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
        </tfoot>
      </table>
      </div>
    </template>
  </split>

  </BasicModal>
</template>

<script lang="ts" name="BankBalanceModal" setup>
  import {ref, toRaw, unref, reactive} from 'vue';
  import {BasicModal, useModalInner, useModal} from '/@/components/Modal';
  import {BasicTable, TableAction, ActionItem, BasicColumn, useTable} from '/@/components/Table';
  import {departBalanceDay, departBalanceData} from "/@/views/full/bank/types/bank.api";
  import {useListPage} from '/@/hooks/system/useListPage';
  import {filterObj, formatAmount} from '/@/utils/common/compUtils';
  import {render} from '/@/utils/common/renderUtils';
  import Split from '/@/components/pt/split/Index.vue'
  import moment from 'dayjs';

  //----------定义变量 开始-------------------------------------------------------------
  const queryParam  = reactive<any>({});
  //标题
  const getTitle    = ref<any>('');
  const bankRunning = reactive<any>({});
  const account     = reactive<any>({});
  const accountList = reactive<any>([]);
  //------------------------------------

  // 初始化
  const [registerModal, {setModalProps, closeModal}] = useModalInner(async (data) => {
    let record = data?.record || {};
    getTitle.value       = record?.title + " __ 审核日期：" + moment(record?.beginDate).format("YYYY-MM-DD") ;
    queryParam.bankId    = record?.bankId;
    queryParam.beginDate = record?.beginDate;
    queryParam.ddlx      = record?.ddlx;
    searchQuery();
  });

  const shbjFmt = ({ text, record }) => {
    if (text && text !== '合计') {
      let value = text == '0' ? '未审' : text == '1' ? '已审' : '未知';
      let color = text == '0' ? 'green' : text == '1' ? 'red' : 'blue';
      if (record.sffs == '4') {
        color = 'purple';
      }
      return render.renderTag(value, color);
    }
  };

  const statusFmt = ({ text }: { text: any }) => {
    const value = render.renderDict(text, 'accountStat');
    if (!text || text == '合计') {
      return text;
    }
    switch (text) {
      case '1':
        return render.renderTag(value, 'green');
      case '2':
        return render.renderTag(value, "purple");
      case '3':
        return render.renderTag(value, "red");
      default:
        return text;
    }
  };

  // 收付方式翻译
  const sffsFmt = ({ text, record }) => {
    if (!text) {
      return ''
    }
    let color : String[] = ['', 'red', '', 'blue', 'purple', 'orange'];
    return render.renderTag(render.renderDict(text, 'sffsType'), color[text])
  };

  // 金额格式化
  const moneyFmt = ({ text, record }) => {
    let color = 'red';
    if (text > 0) {
      color = 'text-green-600';
    } else if (text < 0) {
      color ='text-purple-600';
    } else {
      color ='text-blue-600';
    }
    return render.renderColor(formatAmount(text), color);
  };

  // --------------右边--列表----------------------------------------
  // 订单列表 - 表头
  const columns: BasicColumn[] = [
    { title: '部门', align: 'center', dataIndex: 'lsddlx', width: 50, customRender: ({ text }) => render.renderDict(text, 'ddlxType') },
    { title: '收支日期', align: 'center', dataIndex: 'jzrq', width: 85 },
    { title: '银行审核', align: 'center', dataIndex: 'lsstat', width: 60, customRender: shbjFmt, },
    { title: '银行收支', align: 'right', dataIndex: 'lslrje', width: 90, customRender: moneyFmt },
    { title: '系统审核', align: 'center', dataIndex: 'xtstat', width: 60, customRender: statusFmt, },
    { title: '系统方式', align: 'center', dataIndex: 'xtsffs', width: 60, customRender: sffsFmt, },
    { title: '系统收支', align: 'right', dataIndex: 'xtlrje', width: 90, customRender: moneyFmt },
    { title: '对账差额', align: 'right', dataIndex: 'lrce', width: 90, className: 'text-rose-600', customRender: ({ text }) => formatAmount(text)},
    { title: '对账结果', align: 'center', dataIndex: 'diffField', width: 60, slots: { customRender: 'diffFmt' },}
  ];

  // 列表页面公共参数、方法
  const loading = ref<boolean>(false);
  const { prefixCls, tableContext } = useListPage({
    designScope: 'bankBalance-check',
    tableProps: {
      rowKey: "jzsj",
      size: "small",
      api: departBalanceDay,
      columns: columns,
      showTableSetting: false,
      showIndexColumn: true, //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 70,
      pagination: false,
      showSummary: true,
      immediate: false,
      summaryFunc: handleSummary,
      afterFetch: (res) => {
        if (res.length <= 0) {
          return
        }
        handleClick(res[0]);
      }
    }
  });

  //注册table数据
  const [registerTable, { reload, setProps, getRawDataSource, redoHeight }] = tableContext;

  // --------------右边--列表----------------------------------------

  // --------------组件--事件----------------------------------------
  //单击行
  let selectRows = reactive<any>({ id: '', lsid: '' , xtid: '', ddlx: '' });
  function handleClick(record) {
    selectRows.id   = record.id;
    selectRows.lsid = record.lsid;
    selectRows.xtid = record.xtid;
    loadBalanceData()
  }

  //双击行
  function handleDblclick(record) {
    //handleEdit();
  }

  function rowClassName(record, index) {
    return record.id === selectRows.id ? 'row-selected' : '';
  }

  /**
   * 查询
   */
  function searchQuery() {
    clearData();
    let params = toRaw(filterObj(queryParam));
    setProps({ searchInfo: params });
    reload();
  }

  function loadBalanceData() {
    clearData();
    let params = {
      lsid: selectRows.lsid,
      xtid: selectRows.xtid,
    }
    departBalanceData(params).then( res => {
      //console.log('departBalanceData', res);
      if (res.success) {
        Object.assign(bankRunning, res.result.bankRunning);
        Object.assign(account, res.result.account);
        Object.assign(accountList, res.result.accountList);
        
        // if (!bankRunning.id ) {
        //   bankRunning.id = '流水未导入';
        //   bankRunning.idcolor = 'text-red-600';
        // }

        // if (!account.id ) {
        //   account.id = '订单未审核';
        //   account.idcolor = 'text-red-600';
        // }
      } else {
        // bankRunning = {};
        // account = {};
      }
    })
  }

  /**
   * 合计
   */
  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource()
    redoHeight();
    if (res) {
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }

  // --------------组件--事件----------------------------------------

  // --------------组件--事件----------------------------------------
  function renderDict(text, code) {
    const value = render.renderDictText(text, code);
    return value;
    //return render.renderTag(value, 'text-blue-500');
  }

  function renderMoney(amount) {
    if (amount) {
      return formatAmount(amount);
    } else {
      return "";
    }
  }

  function renderStatus(text, type) {
    if (text == null || text === undefined || text === '' || text === '合计') {
      return text || '';
    }
    try {
      const color = text == '0' ? 'text-green-500' : text == '3' ? 'text-red-500' : 'text-blue-500';
      const value = render.renderDictText(text, 'accountStat');
      if (type == 'color') {
        return color;
      } else {
        return value;
      }
    } catch (error) {
      console.error('Error in statusFmt:', error);
      return text || '';
    }
  }

  // 用 for 清空 bankRunning 和 account 数据 
  function clearData() {
    for (let key in bankRunning) {
      delete bankRunning[key];
    }
    for (let key in account) {
      delete account[key];
    }
    for (let key in accountList) {
      delete accountList[key];
    }
  }
</script>

<style lang="less" scoped>
  .orderTable th, .orderTable td  {
    height: 38px;
  }
</style>
